﻿@model BusinessLayer.VDataEntities.VReport
@{
    ViewBag.Title = @Model.Name;
    Layout = "~/Views/Shared/Layout.Mobile.cshtml";
}
<script src="@TrialManagementTool.Helper.UrlHelper.alterContent("Scripts/mobilejs/sm-extend.min.js")"></script>
<link href="@TrialManagementTool.Helper.UrlHelper.alterContent("Content/zzsc.css")" rel="stylesheet" />
<script src="@TrialManagementTool.Helper.UrlHelper.alterContent("Scripts/mobilejs/zooming.js")"></script>
<script src="@TrialManagementTool.Helper.UrlHelper.alterContent("Scripts/mobilejs/lrz.all.bundle.js")"></script>

<script>

    var datasource;

    $.ajax({
        url: fixUrl("api/Trial/GetAllFieldsDataSource"),
        success: function (data) {
            datasource = data;
        }
    })

    function GenerateSource(id, fileid, item, needgroup) {
        var content = "";
        if (datasource == undefined) {
            setTimeout(function () { GenerateSource(id, fileid, item, needgroup) }, 50);
        } else {
            if (needgroup == true) {
                $("#trial_" + id).append("<optgroup>")
            }
            $("#trial_" + id).append("<option value='" + 0 + "'>" + '请选择' + "</option>");
            $.each(datasource[fileid], function (index, value) {
                $("#trial_" + id).append("<option  value='" + value.Value + "'>" + value.Description + "</option>");
            })
            if (needgroup == true) {
                $("#trial_" + id).append("</optgroup>")
            }
            if (item > 0) {
                $("#trial_" + id).val(item);
            }
        }
    }
    function DisplayCheckbox(id, value) {
        if (value == "true") {
            $("#trial_" + id).prop("checked", "checked");
            $("#fengbichkdesc" + id).html("是");
        } else {
            $("#fengbichkdesc" + id).html("否");
        }
    }
    function CreateDateTime(value, target) {
        if (value != "") {
            $("#" + target).calendar({
                value: [FormatDate(value)]
            })
        } else {
            value = new Date();
            $("#" + target).calendar({
                value: [FormatDate(value)]
            });
            $("#" + target).val('');
        }
    }
    function FormatDate(strTime) {
        var date = new Date(strTime);
        return date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
    }
    function CreateElement(name, type, id, need, value, fieldId) {
        //1.文字,2:数字,3:时间,4:下拉框,5;checkbox
        var content = "";
        if (type == "1") {
            content = '<li><div class="item-content"><div class="item-media"></div><div class="item-inner">' +
   '<div class="item-title label marr10">' + name + GenerateFlag(need) + '</div><div class="item-input"><input type="text" name=' + id + ' data-type="text" data-need="' + need + '" data-desc="' + name + '" id=trial_' + id + ' value="' + value + '" maxlength="100" placeholder="请输入"></div></div></div></li>';
        } else if (type == "3") {
            content = '<li><div class="item-content"><div class="item-media"></div><div class="item-inner">' +
   '<div class="item-title label marr10">' + name + GenerateFlag(need) + '</div><div class="item-input"><input type="text" name=' + id + ' data-type="time" " data-need="' + need + '" data-desc="' + name + '" id=trial_' + id + ' class="datetime" value="' + value + '" placeholder="请选择"></div></div></div></li>';
        } else if (type == "5") {
            content = '<li><div class="item-content"> <div class="item-media"><i class="icon icon-form-toggle"></i></div><div class="item-inner">' +
           ' <div class="item-title label marr10">' + name + GenerateFlag(need) + '</div><div class="item-input"><label class="label-switch"><input type="checkbox" name=' + id + ' data-type="checkbox" onchange="UpdateCheckboxDesc(' + id + ')"  data-need="' + need + '" data-desc="' + name + '" id=trial_' + id + '><div class="checkbox"><span id="fengbichkdesc' + id + '" style="margin-left:60px"></div>' +
           ' </label></div> </div></div></li>';
        } else if (type == "2") {
            content = '<li><div class="item-content"><div class="item-media"></div><div class="item-inner">' +
'<div class="item-title label marr10">' + name + GenerateFlag(need) + '</div><div class="item-input"><input type="number" name=' + id + ' data-type="number" data-need="' + need + '" data-desc="' + name + '" id=trial_' + id + ' value="' + value + '" maxlength="100" placeholder="请输入"></div></div></div></li>';
        } else if (type = "4") {
            content = '<li><div class="item-content"><div class="item-media"></div><div class="item-inner">' +
'<div class="item-title label marr10">' + name + GenerateFlag(need) + '</div><div class="item-input"><select name=' + id + ' data-type="select" data-need="' + need + '" data-desc="' + name + '" id=trial_' + id + '><select></div></div></div></li>';
        }
        $(".list-block ul").append(content);
        if (type == 4) {
            if (name == "作物药物反应程度") {
                GenerateSource(id, fieldId, value, true);
            } else {
                GenerateSource(id, fieldId, value, false);
            }
        } else if (type == 5) {
            DisplayCheckbox(id, value);
        } else if (type == 3) {
            CreateDateTime(value, "trial_" + id);
        }
    }
    function GenerateFlag(need) {
        if (need == 'True') {
            return '<span class="mark">&nbsp;&nbsp;*</span>';
        } else { return ''; }
    }

    function CreateImagePreview(id, source, status) {
        var content = '<img class=\"img_preview\" name="uploadimage" id="img_' + id + '" data-action="zoom" src="' + source + '"/>';
        if (status == 0 || status == 1) {
            content += '<img src=' + fixUrl("Images/del.png") + ' id=img_icon_' + id + ' style=\"height:15px;margin-top:-30px;margin-left:-20px;cursor:pointer;\"  onclick=\"DeleteImage(\'' + id + '\')\" />';
        }
        content += '<input type="hidden" name="imagesource" data-source="fromlocal"  id="hid_ipt_img_' + id + '" >'

        $("#spaninput").before(content);
    }
    function UpdateCheckboxDesc(id) {
        if ($("#trial_" + id).is(':checked') == true) {
            $("#fengbichkdesc" + id).html("是");
        } else {
            $("#fengbichkdesc" + id).html("否");
        }
    }
</script>
<style>
    .list-block {
        /*width: 90%;*/
        margin: 0 auto;
    }

    .content {
        width: 100%;
    }

    .col-50 {
        margin-left: 25% !important;
    }

    .item-content {
        font-size: 14px;
    }

    textarea {
        color: #000000;
    }

    .item-input {
        margin-left: 10px;
    }

    .list-block .item-media + .item-inner {
        margin-left: 0.5rem;
    }
</style>
<div class="page-group">
    <div class="page page-current" id="newReport">
        <div class="headClass">@Model.headTitle</div>
        <div class="content" style="width:95%;margin-top:40px">
            <form name="reportitem" id="formid" method="post" enctype="multipart/form-data" action="@TrialManagementTool.Helper.UrlHelper.alterContent("TrialMobile/FinalReport")">
                <div class="list-block">
                    <ul>
                        <!-- Text inputs -->
                        <li>
                            @for (int i = 0; i < Model.inputFields.Count(); i++)
                            {
                                <script>CreateElement('@Model.inputFields[i].Name', '@Model.inputFields[i].DataType', '@Model.inputFields[i].ID', '@Model.inputFields[i].IsMandary', '@Model.inputFields[i].Value', '@Model.inputFields[i].FieldID')</script>
                            }

                        </li>
                        @if (Model.IsObserve == true)
                        {
                            <li style="margin-left:0.5rem;min-height:120px">
                                <div class="item-title label marr10" style="font-size:14px">图片</div>
                                <div class="img-preview">
                                    <div id="show">
                                        <img id="spaninput" src="@TrialManagementTool.Helper.UrlHelper.alterContent("Images/addNewImage.png")" class="img_preview" style="position:relative" />
                                        <input type="file" id="fileSelect" accept="image/*" multiple="multiple" style="opacity: 0;position:absolute;margin-left:-90px" class="img_preview" onchange="upload(this)">
                                        @for (int i = 0; i < Model.Images.Count(); i++)
                                        {
                                            <script>
                                                CreateImagePreview('@Model.Images[i].ID', '@System.Text.Encoding.UTF8.GetString(Model.Images[i].Image)', '@Model.trialSite.Status');
                                            </script>
                                        }
                                        @*限制图片数为6张,状态2,3已提交,已完成*@
                                        @if (Model.Images.Count() >= 6 || Model.trialSite.Status == 2 || Model.trialSite.Status == 3)
                                        {
                                            <script>
                                                $("#spaninput").css("display", "none");
                                                $("#fileSelect").css("display", "none");
                                            </script>
                                        }
                                    </div>
                                </div>
                            </li>
                        }
                        
                    </ul>
                </div>
            </form>
            <div class="row" style="padding:15px">
                @if (Model.trialSite.Status == 0 || Model.trialSite.Status == 1)
                {
                    <div class="col-40" style="margin-left:12%">
                        <a href="#" class="button button-big button-fill button-success " style="height:40px;line-height:40px" onclick="location.href='@TrialManagementTool.Helper.UrlHelper.alterContent("TrialMobile/ProcessManagement?id=" + Model.ReportID)'">返回</a>
                    </div> <div class="col-40" style="margin-left:12%"> <a href="#" class="button button-big button-fill button-success " style="height:40px;line-height:40px" onclick="Save()">保存</a> </div> }
                else
                { <div class="col-50"> <a href="#" class="button button-big button-fill button-success " style="height:40px;line-height:40px" onclick="location.href='@TrialManagementTool.Helper.UrlHelper.alterContent("TrialMobile/ProcessManagement?id=" + Model.ReportID)'">返回</a> </div> }
            </div>
        </div>
        <div style="position:absolute;right:0;top:100px">
            <a class="filterArea" onclick="loadPage()"> <img src="@TrialManagementTool.Helper.UrlHelper.alterContent("Images/fangan.png")" class="fangan" />  </a>
        </div>
    </div>
    <div class="page" id="purpose">
        <header class="bar bar-nav">
            <a class="button button-link button-nav pull-left " href="#newReport">
                <span class="icon icon-left"></span>
                返回
            </a>
            <h1 class='title'>示例方案</h1>
        </header>
        <div class="content" style="width:90%">

            @{var data = new ViewDataDictionary();

            data.Add("TrialGuideID", @Model.TrialGuideID);
            Html.RenderPartial("Purpose", null, data); }
        </div>
    </div>
</div>

<script>
    Zepto(function ($) {
        if (!('@Model.trialSite.Status' == 0 || '@Model.trialSite.Status' == 1)) {
            $("input[type=text]").attr("disabled", "disbaled");
            $("input[type=number]").attr("disabled", "disbaled");
            $("input[type=checkbox]").attr("disabled", "disbaled");
            $("textarea").attr("disabled", "disbaled");
            $("select").attr("disabled", "disbaled");
        }
        $("#comment").val(FormatTextAreaValue('@Model.Comments'));
    })
    function upload(target) {
        $.showIndicator();
        var num = target.files.length;
        if (document.getElementsByName("uploadimage").length + num > 6) {
            $.toast("单个报告最多允许上传6张图片");
            $.hideIndicator();
        } else {
            for (var i = 0; i < num; i++) {
               
                    lrz(target.files[i], { width: 640 })
                    .then(function (rst) {
                        var xhr = new XMLHttpRequest();
                        xhr.open('POST', fixUrl('TrialMobile/UpdateImage'));
                        xhr.onload = function (data) {
                            if (xhr.status === 200 && data.srcElement.response > 0) {
                                CreateImagePreview(data.srcElement.response, rst.base64, 1)
                                $.hideIndicator();
                                if (document.getElementsByName("uploadimage").length == 6) {
                                    $("#spaninput").css("display", "none");
                                }
                            } else {
                                $.hideIndicator();
                                $.toast("图片处理失败");
                            }
                        };

                        xhr.onerror = function () {
                            // 处理错误
                            $.hideIndicator();
                            $.toast("图片处理失败");
                        };

                        xhr.upload.onprogress = function (e) {
                            // 上传进度
                            var percentComplete = ((e.loaded / e.total) || 0) * 100;
                        };
                        // 添加参数和触发上传
                        rst.formData.append('ReportID', '@Model.ID');
                        // 触发上传
                        xhr.send(rst.formData);

                        return rst;

                    })
                    .catch(function (err) {
                        $("ERROR ")
                        $.hideIndicator();
                    })
                    .always(function () {

                    });
                
            }
        }
    };

    function loadPage() {
        $.router.load("#purpose");
        init();
    }

    function DeleteImage(id) {
        $.ajax({
            url: fixUrl("api/trial/DeleteImage"),
            data: { id: id },
            type: "post",
            success: function (data) {

            },
            error: function (data) {
                if (data.statuscode == "401") {
                    $.alert('登录超时');
                } else {
                    $.alert('删除失败');
                }
            }
        })
        $("#img_" + id).remove();
        $("#img_icon_" + id).remove()
        $("#spaninput").css("display", "inline");
        $("#fileSelect").css("display", "inline");
        $("#hid_ipt_img_" + id).remove();
    }

    function Save() {
        var input = $("#formid").serializeArray();
        //var errmessage = "";
        var postdata = { inputData: [], comment: {}, reportid: {}, imagesource: [], imagedelete: [] }
        $.each(input, function (index, value) {
            var id = value.name;
            if (id == "imagesource") {//图片

            } else {
                //if ($("#trial_" + id).data("need") == "True"&&$("#trial_" + id).val()==""&&$("#trial_" + id).val()==0) {
                //    errmessage += $("#trial_" + id).data("desc") + "不能为空</br>";
                //}

                if ($("#trial_" + id).data("type") == "checkbox") {
                    postdata.inputData.push({ ID: id, Value: $("#trial_" + id).is(':checked') });
                } else if ($("#trial_" + id).data("type") == "select") {
                    if (value.value > 0) {
                        postdata.inputData.push({ ID: id, Value: value.value });
                    } else {
                        postdata.inputData.push({ ID: id, Value: "" });
                    }
                } else {
                    postdata.inputData.push({ ID: id, Value: value.value });
                }
            }
        })

        //fix checkbox form searize
        $.each($("input[type='checkbox']"), function (index, value) {
            postdata.inputData.push({ ID: value.name, Value: $("#" + value.id).attr('checked') });
        })
        //if ($("#comment").val()!="") {
        //    postdata.comment = encodeTextAreaString($("#comment").val());
        //}
        postdata.reportid = '@Model.ID';
        $.ajax({
            url: fixUrl("api/trial/UpdateInputs"),
            data: postdata,
            type: "post",
            beforeload: $.showPreloader('正在保存页面数据...'),
            success: function (data) {
                $.hidePreloader();
                if (data.status == "Success") {
                    $.toast("操作成功,返回处理列表");
                    setTimeout(function () {
                        location.href = fixUrl("trialMobile/ProcessManagement?id=@Model.ReportID");
                    }, 2000)
                } else {
                    $.alert('保存失败,请重试');
                }

            },
            error: function (data) {
                $.hidePreloader();
                if (data.statuscode == "401") {
                    $.alert('登录超时');
                } else {
                    $.hidePreloader();
                    $.alert('保存失败,请重试');
                }
            }
        })

    }
</script>
